package org.example.datasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        String dataSourceKey = SubjectContext.getDataSourceKey();
        log.info("determineCurrentLookupKey: {}", dataSourceKey);
        return dataSourceKey;
    }

    // 增强：动态添加数据源
    public void addDataSource(String dsKey, DataSource dataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(getResolvedDataSources());
        targetDataSources.put(dsKey, dataSource);
        setTargetDataSources(targetDataSources);
        afterPropertiesSet(); // 刷新数据源
        log.info("afterPropertiesSet getResolvedDataSources: {}", getResolvedDataSources());
    }
}
